/*
    Copyright 2011 Anishek Agarwal(anishek@gmail.com), Ashish Mishra(ashish@ashishmishra.in)
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.thoughtworks.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;

public class Source {
    private String content;
    private SourceType sourceType;

    public Source(File file) {
        try {
            content = readFile(file);
        } catch (IOException e) {
            new IllegalArgumentException(e);
        }
        sourceType = determineSourceType(file);
    }

    SourceType determineSourceType(File file) {
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".java")) {
            return SourceType.JAVA;
        }
        if (fileName.endsWith(".vm")) {
            return SourceType.VElOCITY;
        }
        return SourceType.NULL;
    }

    public boolean contains(String propertyKey) {
        return sourceType.containsProperty(propertyKey, content);
    }

    private String readFile(File file) throws IOException {
        byte[] bytesRead = new byte[4096];
        FileInputStream stream = new FileInputStream(file);
        StringWriter writer = new StringWriter();
        for (int numberOfBytesRead = stream.read(bytesRead); numberOfBytesRead != -1; numberOfBytesRead = stream.read(bytesRead)) {
            writer.append(new String(bytesRead, 0, numberOfBytesRead));
        }
        return writer.toString();
    }
}
